//
//  OAuthViewController.swift
//  WeiBo2017
//
//  Created by 王璐 on 2017/4/21.
//  Copyright © 2017年 wl. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {

    fileprivate lazy var webView = UIWebView()
    
    //MARK : 视图生命周期
    override func loadView() {
        view = webView
        
        title = "登录新浪微博"
//        navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName:UIFont.systemFont(ofSize: 16)]
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(
            title: "取消",
            style: .plain,
            target: self,
            action: #selector(OAuthViewController.clickCloseButton))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(
            title: "自动登录",
            style: .plain,
            target: self,
            action: #selector(OAuthViewController.clickAutoLoginBtn))
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //在纯代码开发中,所有的view都要指定背景颜色
        view.backgroundColor = UIColor.white
        //webView加载登录界面
        webView.loadRequest(URLRequest(url: NetworkTools.sharedTools.oauthUrl as URL))
        webView.delegate = self
    }

    /// 监听方法
    @objc fileprivate func clickCloseButton(){
        
        dismiss(animated: true, completion: nil)
    }
    
    
    @objc fileprivate func clickAutoLoginBtn(){
        let js = "document.getElementById('userId').value='15665339642';" + "document.getElementById('passwd').value='wanglu1314151';"
        webView.stringByEvaluatingJavaScript(from:js)
        
    }

}

// MARK: - webView的代理方法
extension OAuthViewController :UIWebViewDelegate {
    
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        /// 判断url是否是回调url
        //如果url不是回调地址就继续加载
        if let urlString = request.url?.absoluteString  {
            if  !urlString.hasPrefix(NetworkTools.sharedTools.redlrectUrl){
                return true
            }
        }
        //1.否则判断回调参数,如果授权成功url中的"查询字符串"包含code参数
        guard let query = request.url?.query, query.hasPrefix("code=") else{
            print("取消授权")
            dismiss(animated: true, completion: nil)
             return false
        }
        //2.获得请求码
        let code = query.substring(from: "code=".endIndex)
        print("请求码=\(code)")
        
        //3.发起网络请求,做后续操作
     NetworkTools.sharedTools.loadAccessToken(code: code) { (result) in
        guard let result = result else {
            print("你的网络不给力")
            return
        }
       //设置用户账户单例的数据
     UserCount.sharedUserCount.updateUserAccount(dict: result)
        
        //发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WLWeiBoLoginSuccessdNotification), object: nil)
        
        //关闭登录界面
        self.clickCloseButton()
        }
        
        
        
        return false
    }
}
